<template>
  <div class="h5-container">
    <NavBar title="我的合同" :onClickLeft="toBack"></NavBar>

    <div class="h5-filter">
      <van-dropdown-menu direction="down" active-color="#1989fa">
        <van-dropdown-item v-model="status" :options="statusData" @change="changeStatus" />
      </van-dropdown-menu>
    </div>
    <!-- 列表 -->
    <van-list
      v-if="list.length || loading"
      class="contracts-body"
      v-model="loading"
      :finished="finished"
      error-text="请求失败，点击重新加载"
      :finished-text="finishedText"
      direction="down"
      :offset="10"
      @load="onLoad">
      <van-cell class="contract-cell" v-for="item in list" :key="item.id" @click="openContract(item)">
        <van-tag size="large" :type="item.FlowStatus.trim() | statusTypeFilter" class="contract-status">
          {{ item.FlowStatus.trim() | flowStatusFilter }}
        </van-tag>
        <div class="contract-cell-text">合同名称：{{ item.FlowName }}</div>
        <div class="contract-cell-text date">
          合同发起时间：{{ item.CreateOn | dateFilter }}
        </div>
        <div class="contract-cell-text date" v-if="['INIT', 'PART', 'WILLEXPIRE'].includes(item.FlowStatus.trim())">
          合同截止日期：{{ item.DeadLine | dateFilter }}
        </div>
      </van-cell>
    </van-list>
    <van-empty v-else class="list-empty" description="暂无数据" />

  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { getH5ContractList, createH5SignUrl } from '@common/api/contract';
import { WORKER_CONTRACT_STATTUS, WORKER_CONTRACT_STATTUS_TEXT } from '@common/consts/status';
import moment from 'moment';
import NavBar from './components/NavBar';

export default {
  name: 'contracts',
  components: {
    NavBar,
  },
  data() {
    return {
      list: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      finished: false,
      status: 'WAITSIGN', // 默认待签署
    };
  },
  computed: {
    ...mapGetters(['token']),
    statusData() {
      const data = [];
      // eslint-disable-next-line no-restricted-syntax
      for (const k in WORKER_CONTRACT_STATTUS_TEXT) {
        data.push({
          text: WORKER_CONTRACT_STATTUS_TEXT[k],
          value: k,
        });
      }
      return data;
    },
    finishedText() {
      return (this.total > (this.currentPage - 1) * this.pageSize && this.total > this.pageSize) ? '加载更多' : '没有更多了';
    },
  },
  filters: {
    dateFilter(time) {
      return time ? moment(time * 1000).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    flowStatusFilter(status) {
      if (status) {
        // eslint-disable-next-line no-restricted-syntax
        for (const k in WORKER_CONTRACT_STATTUS) {
          if (WORKER_CONTRACT_STATTUS[k].includes(status)) {
            return WORKER_CONTRACT_STATTUS_TEXT[k];
          }
        }
      }
      return '';
    },
    statusTypeFilter(status) {
      const statusTypeMap = {
        WAITSIGN: 'warning',
        PART: 'warning',
        SIGNED: 'success',
        FAILED: 'danger',
      };
      if (status) {
        // eslint-disable-next-line no-restricted-syntax
        for (const k in WORKER_CONTRACT_STATTUS) {
          if (WORKER_CONTRACT_STATTUS[k].includes(status)) {
            return statusTypeMap[k];
          }
        }
      }
      return '';
    },
  },
  created() {
    this.status = this.$route.query?.contractStatus || 'WAITSIGN';
    this.getList();
  },
  methods: {
    // 返回
    toBack() {
      this.$router.push({
        path: '/',
      });
    },

    changeStatus() {
      this.list = [];
      this.currentPage = 1;
      this.total = 0;
      this.finished = false;
      this.getList();
    },

    async getList() {
      try {
        this.loading = true;
        const res = await getH5ContractList({
          limit: this.pageSize,
          offset: (this.currentPage - 1) * this.pageSize,
          contractType: 2, // 劳动合同
          status: this.status,
        });
        if (res?.data?.contracts?.length) {
          if (this.currentPage === 1) {
            this.list = [...res?.data?.contracts];
          } else {
            this.list.push(...res?.data?.contracts);
          }
        }
        this.total = res?.data?.totalCount || 0;
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.log('error=====', error);
      }
    },

    openContract(item) {
      try {
        if (item && ['INIT', 'PART', 'WILLEXPIRE'].includes(item.FlowStatus)) {
          const flowApproverInfos = JSON.parse(item.FlowApproverInfos);
          if (item.FlowStatus === 'PART' && flowApproverInfos[1].ApproveStatus === 'ACCEPT') {
            return false;
          }
          createH5SignUrl({ flowId: item.FlowId }).then((res) => {
            const flowUrlInfos = res.data?.FlowApproverUrlInfos;
            const urlInfo = flowUrlInfos[0];
            if (urlInfo) {
              this.$router.push({
                path: '/contractIframe',
                query: urlInfo.SignUrl ? { url: urlInfo.SignUrl } : '',
              });
              // window.location.href = (urlInfo.SignUrl);
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    onLoad() {
      this.currentPage = this.currentPage + 1;
      if (this.total !== 0 && this.total > (this.currentPage - 1) * this.pageSize && this.total > this.pageSize) {
        this.getList();
      } else {
        this.finished = true;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.contracts-body {
  position: relative;
  width: 100%;
  padding-top: 190px;
  .contract-cell {
    position: relative;
    padding: 30px;
    font-size: 28px;
    border-bottom: 1px solid #eee;
    .contract-status {
      position: absolute;
      right: 0;
      top: 30px;
      color: #fff;
      padding: 10px;
      border-radius: 4px;
    }
    .contract-cell-text {
      line-height: 50px;
      padding-right: 110px;
      &.date {
        font-size: 24px;
        color: #666;
      }
    }
  }
}
.load-more {
  font-size: 28px;
  text-align: center;
  padding: 40px 0;
}
</style>
